/**
 * Fun msg 提示框
 * Fun alert modal提示框
 * Fun padLeftZero 左边自动补全0
 * Fun filePreview 单文件预览
 * Fun previewImage 多图预览
 * Fun buildTreeList 创建树形组件需要的数据格式
 * Fun getfileName 获取文件名称
 * Fun Download 下载文件
 * Fun IsJson 是否时Json格式
 * Fun multiFilter 数组筛选
 * Fun newGuid 获取Guid
 * Fun getAgeFromIdCard 根据身份证获取年龄
 * Fun getAgeFromBirth 根据生日获取年龄
 * Fun randomString 随机字符串
 */


/**
 * 提示框
 */
function msg(res,callback){
	var message = '请求成功！';
	if(typeof res === 'object'){
		if(res.errors && res.errors.length > 0){
			message = res.errors[0];
		} else {
			message = res.message;
		}
	} else if(typeof res === 'string'){
		message = res;
	} 
	
	uni.showToast({
		icon:'none',
		title:message
	});
	if(typeof callback === 'function'){
		setTimeout(function(){
			callback();
		},1500);
	}
}
/**
 * modal提示框
 */
function alert(param){
	var option = {
		title:'提示',
		content:'',
		showCancel:false,
		confirm:null
	}
	option = Object.assign(option,param);
	uni.showModal({
		title:option.title,
		content:option.content,
		showCancel:option.showCancel,
		success:function(res){
			if(res.confirm){
				if(option.confirm) option.confirm();
			}
		}
	});
}
/**
 * 左边自动补全0
 */
function padLeftZero(value) {
    return ('00' + value).substr(value.length);
}

/**
 * 单文件预览
 * @param {Object} url
 */
function filePreview(url){
	var fileArray = url.split('|');
	var url = fileArray[0];
	var fileName = fileArray[1];
	if(!fileName){
		fileName =  url.substring(url.lastIndexOf("/")+1);
	}
	var extName = fileName.substring(fileName.lastIndexOf(".")+1);
	var DocExtNames = 'doc|xls|ppt|pdf|docx|xlsx|pptx';
	var ImgExtNames = 'jpg|jpeg|png|gif';
	if(DocExtNames.indexOf(extName) > -1){
		Download(url);
	} else if(ImgExtNames.indexOf(extName) > -1){
		previewImage(0,[url]);
	}
}
/**
 * 多图预览
 * @param {Object} cur
 * @param {Object} imgs
 */
function previewImage(cur,imgs){
	uni.previewImage({
		urls: imgs,
		current: cur ? cur : 0,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
			success: function(data) {
				//console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
			},
			fail: function(err) {
				console.log(err.errMsg);
			}
		}
	});
}

function getfileName(url){
	var fileArray = url.split('|');
	var url = fileArray[0];
	var fileName = fileArray[1];
	if(!fileName){
		fileName =  url.substring(url.lastIndexOf("/")+1);
	}
	return fileName;
}
function Download(url){
	uni.showLoading({
		title:'下载中'
	});
	var url = url.replace('http:','https:');
	var fileName = url.substring(url.lastIndexOf("/")+1);
	uni.downloadFile({
		url: url,
		success: (res) => {
			uni.hideLoading();
			if (res.statusCode === 200) {
				uni.saveFile({
					tempFilePath: res.tempFilePath,
					success: function (res) {
						uni.openDocument({
							filePath:res.savedFilePath
						});
					},
					fail:function(res){
						uni.showToast({
							title:'文件保存失败'
						});
						console.log(res);
					}
				});
			}
		},
		fail:function(res){
			uni.hideLoading();
			uni.showToast({
				title:'文件加载失败'
			});
			console.log(res);
		}
	});
}

function buildTreeList(obj,param){
	var option = {
		idKey:'id',
		pidKey:'pid',
		rootId:0,
		value:''
	}
	option = Object.assign(option,param);
	var group = [];
	obj.forEach((item)=>{
		if(item[option.idKey] == option.value){
			item.checked = true;
		}
		if(item[option.idKey] != 0 && item[option.pidKey] != item[option.idKey]) {
			if(!group[item[option.pidKey]]) group[item[option.pidKey]] = [];
			group[item[option.pidKey]].push(item);
		}
	});
	function getTree(arr){
		if(!arr) return [];
		arr.forEach((item)=>{
			if(!item['children']) item['children'] = [];
			item['children'] = getTree(group[item[option.idKey]]);
		});
		return arr;
	}
	var tree = getTree(group[option.rootId]);
	return tree;
}

/**
 * 是否是JSON
 */
function IsJson(value) {
    if (!value) {
        return false;
    }
    try {
        var obj = JSON.parse(value);
        if (typeof obj == 'object' && obj) {
            return true;
        }
    } catch (e) {
        return false;
    }
    return false;
}

function multiFilter(array, filters) {
	var filterKeys = Object.keys(filters);
	return array.filter((item) => {
		return filterKeys.every(key => {
			if(!filters[key].length) return true;
			var value = item[key];
			return !!~filters[key].indexOf(value);
		});
	});
}

function S4() 
{   
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);   
} 
function newGuid() 
{   
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());   
}

//根据身份证获取年龄
function getAgeFromIdCard(idCard) {
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - idCard.substring(6, 10) - 1;
    if (idCard.substring(10, 12) < month || idCard.substring(10, 12) == month && idCard.substring(12, 14) <= day) {
        age++;
    }
    return age;
}

//根据生日取年龄
function getAgeFromBirth(birthDay) {
	var birthDay = birthDay.split('-');
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - birthDay[0] - 1;
    if (birthDay[1] < month || birthDay[1] == month && birthDay[2] <= day) {
        age++;
    }
    return age;
}

//清除富文本中图片样式
function convert (html) {
	let str = html.replace(/<img[^>]*>/gi, function (match, capture) {
		return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="max-width:100%;height:auto;vertical-align: bottom;"');
	});
	return str;
}
function randomString(length) {
	const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let result = '';
    for (let i = length; i > 0; --i) {
		result += chars[Math.floor(Math.random() * chars.length)];
	}
    return result;
}

/**
 * 格式化显示文本
 * @param {Object} str
 * @param {Object} type
 */
function formatText(str, type){
	let fmt = '';
	let tem_str = str;
	switch(type){
		case 1: // 名字
			let len = tem_str.length;
			if(len > 2){
				fmt = tem_str.substring(0,1)+"*"+tem_str.substring(len,len-1);
			} else {
				fmt = tem_str.substring(0,1)+"*";
			}
		break;
		case 2: // 手机号
			fmt = tem_str.substring(0,3)+"******"+tem_str.substring(11,8);
		break;
		case 3: // 身份证号
		break;
	}
	return fmt;
}

/**
 * 计算两个坐标点的距离
 * @param {Object} lat1
 * @param {Object} lng1
 * @param {Object} lat2
 * @param {Object} lng2
 */
function getDistance(lat1, lng1, lat2, lng2) {
	const radLat1 = lat1 * Math.PI / 180.0;
	const radLat2 = lat2 * Math.PI / 180.0;
	const a = radLat1 - radLat2;
	const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
		.pow(Math.sin(b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toFixed(2);
	return s; // 返回公里数
}
// 简陋版屏蔽二次点击事件重复触发
function debounceEvent (fn, wait = 500) {
	let timer = null
	return function() {
		var context = this
		var args = arguments
		if (timer) return
		fn.apply(context, args);
		timer = setTimeout(() => {
			timer = null
			clearTimeout(timer)
		}, wait)
	}
}

module.exports={
	filePreview,
	getfileName,
	previewImage,
	padLeftZero,
	buildTreeList,
	multiFilter,
	newGuid,
	msg,
	alert,
	getAgeFromBirth,
	convert,
	randomString,
	formatText,
	getDistance,
	debounceEvent
}